package backend

import (
	"encoding/json"
	"log"
	"net/http"
	"sync"

	"oil-drilling-monitor/backend/drill"
)

type Message struct {
	Type    string `json:"type"`
	Payload []byte `json:"payload"`
}

// WebSocketClient WebSocket客户端结构
type WebSocketClient struct {
	conn *WebSocketWrapper
}

// Server WebSocket服务器结构
type Server struct {
	clients map[string]*WebSocketClient
	mutex   sync.RWMutex
}

// NewServer 创建新的Server实例
func NewServer() *Server {
	return &Server{
		clients: make(map[string]*WebSocketClient),
	}
}

// BroadcastMessage 广播消息给所有非sender客户端
func (s *Server) BroadcastMessage(message Message) {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	for _, client := range s.clients {
		err := client.conn.WriteMessage(message)
		if err != nil {
			log.Printf("Error broadcasting message to client: %v", err)
		}
	}
}

// WriteDrillConfigHandler 处理写入钻机配置的POST请求
func (s *Server) WriteDrillConfigHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var config drill.DrillConfig
	if err := json.NewDecoder(r.Body).Decode(&config); err != nil {
		http.Error(w, "Invalid JSON format: "+err.Error(), http.StatusBadRequest)
		return
	}

	manager := drill.Get()
	if err := manager.WriteConfig(config); err != nil {
		http.Error(w, "Failed to write config: "+err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]string{"status": "success", "message": "Config written successfully"})
}

// GetDrillConfigHandler 处理查询最新钻机配置的GET请求
func (s *Server) GetDrillConfigHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	manager := drill.Get()
	config, err := manager.GetLatestConfig()
	if err != nil {
		// If no config found, return the current config (which includes defaults)
		config = manager.GetCurrentConfig()
	}
	log.Println("GetDrillConfigHandler:", config)
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(config)
}
